<template>
  <div class="glitch-container">
    <div class="glitch-layer scanlines"></div>
    <div v-if="isGlitching" class="glitch-layer rgb-split" :style="glitchStyle"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const isGlitching = ref(false)
const glitchStyle = ref({})

let glitchInterval = null

const triggerGlitch = () => {
  isGlitching.value = true
  
  // 随机偏移量
  const offsetX = (Math.random() - 0.5) * 10
  const offsetY = (Math.random() - 0.5) * 10
  const skew = (Math.random() - 0.5) * 5
  
  glitchStyle.value = {
    transform: `translate(${offsetX}px, ${offsetY}px) skew(${skew}deg)`,
    clipPath: `inset(${Math.random() * 50}% 0 ${Math.random() * 50}% 0)`
  }
  
  // 短暂的故障效果
  setTimeout(() => {
    isGlitching.value = false
  }, 100 + Math.random() * 200)
}

onMounted(() => {
  // 随机触发故障效果
  const scheduleNextGlitch = () => {
    const delay = 3000 + Math.random() * 5000 // 3-8秒
    glitchInterval = setTimeout(() => {
      triggerGlitch()
      scheduleNextGlitch()
    }, delay)
  }
  
  scheduleNextGlitch()
  
  // 清理
  onUnmounted(() => {
    if (glitchInterval) {
      clearTimeout(glitchInterval)
    }
  })
})
</script>

<style scoped>
.glitch-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 100;
}

.glitch-layer {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

/* 扫描线效果 */
.scanlines {
  background: linear-gradient(
    to bottom,
    rgba(255, 255, 255, 0) 50%,
    rgba(0, 243, 255, 0.02) 51%,
    rgba(0, 243, 255, 0.02) 100%
  );
  background-size: 100% 4px;
  animation: scanlines-move 8s linear infinite;
  opacity: 0.5;
}

@keyframes scanlines-move {
  0% {
    background-position: 0 0;
  }
  100% {
    background-position: 0 100%;
  }
}

/* RGB通道分离效果 */
.rgb-split {
  background: transparent;
  animation: rgb-split-anim 0.2s steps(2, end);
}

@keyframes rgb-split-anim {
  0% {
    filter: 
      drop-shadow(2px 0 0 rgba(255, 0, 0, 0.8))
      drop-shadow(-2px 0 0 rgba(0, 255, 255, 0.8));
  }
  50% {
    filter: 
      drop-shadow(-2px 0 0 rgba(255, 0, 0, 0.8))
      drop-shadow(2px 0 0 rgba(0, 255, 255, 0.8));
  }
  100% {
    filter: 
      drop-shadow(0 2px 0 rgba(255, 0, 0, 0.8))
      drop-shadow(0 -2px 0 rgba(0, 255, 255, 0.8));
  }
}

/* 随机像素条故障 */
.rgb-split::before,
.rgb-split::after {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  height: 2px;
  background: rgba(99, 102, 241, 0.5);
  animation: glitch-bars 0.3s infinite;
}

.rgb-split::before {
  top: 20%;
}

.rgb-split::after {
  top: 60%;
  animation-delay: 0.15s;
}

@keyframes glitch-bars {
  0%, 100% {
    transform: translateX(0);
    opacity: 0;
  }
  50% {
    transform: translateX(calc(-50px + 100px * var(--random, 0.5)));
    opacity: 1;
  }
}
</style>

